package com.example.timingapplication.workers

import android.content.Context
import android.content.Intent
import android.provider.Settings
import android.util.Log
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.example.timingapplication.MainActivity
import com.example.timingapplication.SettingsManager
import com.example.timingapplication.StringUtils
import java.util.Calendar
import java.util.concurrent.TimeUnit

class DingTalkWorker(
    val context: Context,
    workerParams: WorkerParameters
) : Worker(context, workerParams) {


    private var settingsManager: SettingsManager = SettingsManager.getInstance(context)
    override fun doWork(): Result {
        return try {
            // 启动钉钉应用
            startDingTalk()

            // 重新调度下一次任务
            rescheduleNextWork()

            Result.success()
        } catch (e: Exception) {
            Log.e("DingTalkWorker", "Failed to start DingTalk", e)
            Result.failure()
        }
    }

    private fun startDingTalk() {
        val dingTalkPackage = "com.alibaba.android.rimet"
        val packageManager = applicationContext.packageManager

        try {
            val intent = packageManager.getLaunchIntentForPackage(dingTalkPackage)
            if (intent != null) {
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                applicationContext.startActivity(intent)
            } else {
                // 如果没有找到钉钉，尝试打开应用市场搜索
                val marketIntent = Intent(Intent.ACTION_VIEW)
                marketIntent.data = android.net.Uri.parse(
                    "market://details?id=$dingTalkPackage"
                )
                marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                applicationContext.startActivity(marketIntent)
            }
        } catch (e: Exception) {
            Log.e("DingTalkWorker", "Error starting DingTalk", e)
        }
    }

    /**
     * 重新调度下一次任务
     */
    private fun rescheduleNextWork() {
        // 确定这是哪个任务（早上还是晚上）
        val isMorningWork = this::class.java.simpleName.contains("Morning", ignoreCase = true) ||
                tags.contains(MainActivity.MORNING_WORK_TAG)

        val isEveningWork = this::class.java.simpleName.contains("Evening", ignoreCase = true) ||
                tags.contains(MainActivity.EVENING_WORK_TAG)

        if (isMorningWork) {
            // 重新调度明天早上的任务 (默认9:00)
            scheduleNextWork(
                MainActivity.MORNING_WORK_TAG, settingsManager.getMorningHour(9),
                settingsManager.getMorningMinute(0)
            )
        } else if (isEveningWork) {
            // 重新调度今晚的任务 (默认22:00)
            scheduleNextWork(
                MainActivity.EVENING_WORK_TAG, settingsManager.getEveningHour(22),
                settingsManager.getEveningMinute(0)
            )
        }
    }

    /**
     * 调度下一次任务
     * @param tag 工作标签
     * @param hourOfDay 小时 (24小时制)
     * @param minute 分钟
     */
    private fun scheduleNextWork(tag: String, hourOfDay: Int, minute: Int) {
        val constraints = Constraints.Builder()
            .setRequiredNetworkType(NetworkType.NOT_REQUIRED)
            .build()

        val delay = calculateDelayToNextOccurrence(hourOfDay, minute)

        val work = OneTimeWorkRequestBuilder<DingTalkWorker>()
            .setInitialDelay(delay, TimeUnit.MILLISECONDS)
            .setConstraints(constraints)
            .addTag(tag)
            .build()

        WorkManager.getInstance(applicationContext)
            .enqueueUniqueWork(tag, ExistingWorkPolicy.KEEP, work)
    }

    /**
     * 计算到下一个指定时间点的延迟（毫秒）
     * @param hourOfDay 小时 (24小时制)
     * @param minute 分钟
     * @return 到下一个指定时间点的延迟毫秒数
     */
    private fun calculateDelayToNextOccurrence(hourOfDay: Int, minute: Int): Long {
        val now = Calendar.getInstance()
        val nextOccurrence = Calendar.getInstance().apply {
            set(Calendar.HOUR_OF_DAY, hourOfDay)
            set(Calendar.MINUTE, minute)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)

            // 如果当前时间已超过指定时间，则推迟到明天
            if (before(now)) {
                // 已经过了今天的时间点，推迟到明天
                add(Calendar.DAY_OF_MONTH, 1)
            }
        }

        return nextOccurrence.timeInMillis - now.timeInMillis
    }
}
